<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowDown, MoreFilled } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const mainRoutes = computed(() => {
  return router.options.routes.find(r => r.path === '/')?.children || []
})

const visibleMenus = ref(8)
const activeMainRoute = ref('')
const activeSubRoute = ref('')

const displayedRoutes = computed(() => mainRoutes.value.slice(0, visibleMenus.value))
const hiddenRoutes = computed(() => mainRoutes.value.slice(visibleMenus.value))

const currentMainRoute = computed(() => {
  return mainRoutes.value.find(r => r.path === activeMainRoute.value)
})

const handleMainMenuSelect = (index: string) => {
  const selectedRoute = mainRoutes.value.find(r => r.path === index)
  if (selectedRoute && selectedRoute.children && selectedRoute.children.length > 0) {
    const firstChild = selectedRoute.children[0]
    router.push(`/${index}/${firstChild.path}`)
  } else {
    router.push(`/${index}`)
  }
}

const handleSubMenuSelect = (index: string) => {
  router.push(index)
}

const handleCommand = (command: string) => {
  if (command === 'logout') {
    userStore.logout()
  } else if (command === 'profile') {
    router.push('/my/profile')
  }
}

const handleConnectionClick = (event: Event) => {
  event.stopPropagation()
  if (!userStore.wsConnected) {
    ElMessageBox.confirm('WebSocket 连接已断开。是否要重新连接？', '连接状态', {
      confirmButtonText: '重新连接',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      userStore.reconnectWebSocket()
      ElMessage.success('正在尝试重新连接...')
    }).catch(() => {
      ElMessage.info('已取消重新连接')
    })
  }
}

const goHome = () => {
  router.push('/')
}

watch(() => route.path, (newPath) => {
  const parts = newPath.split('/')
  if (parts.length >= 2) {
    activeMainRoute.value = parts[1] || ''
    if (parts.length >= 3) {
      activeSubRoute.value = `${parts[1]}/${parts[2]}`
    }
  }
}, { immediate: true })
</script>

<template>
  <el-container class="layout-container">
    <el-header>
      <div class="header-content">
        <div class="header-left">
          <img src="/logo.png" alt="Logo" class="logo" @click="goHome">
        </div>
        <div class="header-center">
          <el-menu mode="horizontal" :default-active="activeMainRoute" @select="handleMainMenuSelect">
            <el-menu-item v-for="route in displayedRoutes" :key="route.path" :index="route.path">
              {{ route.name }}
            </el-menu-item>
            <el-sub-menu index="more" v-if="hiddenRoutes.length > 0">
              <template #title>
                <el-icon><more-filled /></el-icon>
              </template>
              <el-menu-item v-for="route in hiddenRoutes" :key="route.path" :index="route.path">
                {{ route.name }}
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              {{ userStore.user?.username }}
              <span 
                :class="['connection-status', { 'connected': userStore.wsConnected, 'disconnected': !userStore.wsConnected }]"
                @click.stop="handleConnectionClick"
              ></span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="logout">注销</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-header>
    
    <el-container class="main-container">
      <el-aside width="200px" v-if="currentMainRoute && currentMainRoute.children">
        <el-menu :default-active="activeSubRoute" class="el-menu-vertical" @select="handleSubMenuSelect">
          <el-menu-item v-for="route in currentMainRoute.children" :key="route.path" :index="`/${currentMainRoute.path}/${route.path}`">
            {{ route.name }}
          </el-menu-item>
        </el-menu>
      </el-aside>
      
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    
    <el-footer>
      鱼鱼鱼出品
    </el-footer>
  </el-container>
</template>

<style scoped>
.layout-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  padding: 0;
  background-color: #409EFF;
  color: white;
}

.header-content {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left .logo {
  height: 40px;
  cursor: pointer;
}

.header-center {
  flex-grow: 1;
  display: flex;
  justify-content: center;
}

.header-center .el-menu {
  display: flex;
  justify-content: flex-start;
}

.header-center .el-menu-item,
.header-center .el-sub-menu {
  flex-shrink: 0;
}

.header-right {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.connection-status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  margin: 0 10px;
}

.connection-status.connected {
  background-color: #67C23A;
}

.connection-status.disconnected {
  background-color: #F56C6C;
}

.main-container {
  flex-grow: 1;
  overflow: hidden;
}

.el-aside {
  background-color: #f0f2f5;
  transition: width 0.3s;
}

.el-menu-vertical {
  height: 100%;
  border-right: none;
}

.el-main {
  padding: 20px;
  overflow-y: auto;
}

.el-footer {
  background-color: #f5f7fa;
  color: #333;
  text-align: center;
  line-height: 60px;
}
</style>
